import Util from '../../utils/util.js';
import Status from '../../utils/status.js';

import {acceptOrder, confirmDeliverOrder, getShopConsoleStat, getShopOrderList} from "../../api/shop";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bottom: 30,
    topHeight: 60,
    current_date: "",

    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    lists: [],
    et_show: true,

    fields: [
      {
        title: "菜单",
        name: "menu_type",
        default_val: 0,
        type: "select",
        level: 1,
        range_key: "title",
        child: Status.menuTypes()
      },
      // {title: "菜单", name: "menu_type", default_val: 0, type: "select", level: 4, child: Status.menuTypes()},
      {title: "状态", name: "status", type: "select", level: 4, child: Status.ordderShopStatus()},
      {title: "送达时间", name: "deliver_time", level: 4, child: Status.deliverTimeRange()},
    ],

    printerTypeDialog: false,
    statDialog: false,
    filter: {},
    printerTypeList: {
      order: "打印订单",
      label: "打印品单",
      stall: "打印档口菜品汇总单",
    },

    orderDetailDialog: false,
    currentOrder: null,
    isCheckAll: false,
    selectIds: [],

    statusList: {
      11: "确认接单",
      12: "确认出餐",
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

    this.setData({
      navH: app.globalData.navHeight,
      barHeight: app.globalData.barHeight || 20,
      current_date: Util.formatTime(6)
      // current_date: "2024.04.11"
    });

    let shopAdmin = wx.getStorageSync("SHOP_ADMIN");
    if (wx.getStorageSync("shop_accessToken")) {
      shopAdmin = Util.isEmpty(shopAdmin) ? null : JSON.parse(shopAdmin);
      if (Util.isEmpty(shopAdmin)) {
        wx.removeStorageSync('shop_accessToken')
        return Util.Tips({title: "请先登录"}, {tab: 4, url: "/pages/console/login"});
      }

      let fields = this.data.fields
      if (shopAdmin.shop_type == 1) {
        fields[0].child = Status.menuTypes();
      } else {
        fields[0].child = Status.menuTypes_1();
      }

      this.setData({
        fields: fields,
        shopAdmin: shopAdmin,
        loadend: false,
        page: 1,
        lists: []
      })

      that.getLists()
      that.initTop();

    } else {
      return Util.Tips({title: "请先登录"}, {tab: 5, url: "../console/login"});
    }
  },

  logout(e) {
    Util.showModelTip("退出账号后将不能查看订单信息，确认退出吗", "温馨提示", "立即退出")
      .then(res => {
        if (res.confirm) {
          wx.removeStorageSync("shop_accessToken")
          wx.removeStorageSync("SHOP_ADMIN")
          wx.redirectTo({
            url: "/pages/console/login"
          })
        }
      })
  },

  changeDate(e) {
    const that = this,
      type = e.currentTarget.dataset.v;

    this.setData({
      current_date: Util.preNextDate(this.data.current_date, type),
      loadend: false,
      loading: false,
      isCheckAll: false,
      selectIds: [],
      page: 1,
      lists: []
    })

    this.getLists();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      printerTypeDialog: false
    })
  },

  showOrderDetail(e) {
    const that = this,
      index = e.currentTarget.dataset.index;

    that.setData({
      orderDetailDialog: true,
      currentOrder: that.data.lists[index] || null
    })

  },

  closeOrderDialog(e) {
    this.setData({
      orderDetailDialog: false,
      currentOrder: null
    })
  },

  copyTxt: function (event) {
    const txt = event.currentTarget.dataset.v;
    if (!txt) return;
    wx.setClipboardData({
      data: txt.toString(),
      success: function (res) {
        return app.Tips({title: "复制成功", hideMask: true})
      }
    })
  },

  getLists() {
    const that = this
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});
    let filter = that.data.filter || {}
    filter['current_date'] = this.data.current_date.replaceAll(".", "-");
    filter['page_num'] = that.data.page;

    getShopOrderList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = Util.SplitArray(list, lists);
      lists.map((e1, idx) => {
        // e1.week = Util.getWeek(e1.menu_end_date)
        e1.day = Util.timeToDate(e1.menu_date, 3)
      })

      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        total: res.data.total,
        page: that.data.page + 1,
        et_show: lists.length > 0,
      });

    }).catch(errmsg => {
      Util.Tips({title: errmsg, hideMask: true});
    }).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  selectOrder(e) {
    const that = this,
      key = e.currentTarget.dataset.index

    if ((!key && key.length == 0))
      return

    let lists = this.data.lists || [];
    lists[key].active = lists[key].active !== true;
    let ids = [];
    lists.map((e1, k1) => {
      if (e1.active == true) {
        ids.push(e1.id)
      }
    })

    let filter = this.data.filter || {}
    if (!Util.isEmpty(filter['ids'])) {
      delete filter["ids"];
    }
    /*if (!Util.isEmpty(ids)) {
      filter['ids'] = ids;
      this.setData({filter: filter})
    }
    */
    this.setData({
      lists: lists,
      selectIds: ids,
      isCheckAll: ids.length != lists.length ? false : true
    })
  },

  checkAll(e) {  //选择所有的
    const that = this;
    let isCheckAll = this.data.isCheckAll
    isCheckAll = isCheckAll !== true;

    let lists = this.data.lists,
      selectIds = [];
    if (isCheckAll) {
      lists.map((e1, k1) => {
        e1.active = true;
        selectIds.push(e1.id)
      })
    } else {
      lists.map((e1, k1) => {
        e1.active = false;
      })
      this.setData({
        selectIds: []
      })
    }

    this.setData({
      lists: lists,
      // selectIds: selectIds,
      isCheckAll: isCheckAll
    })

  },

  changeFilterFun(e) {
    const that = this;
    let filter = that.data.filter || {}
    if (e.detail) {
      if (Util.isEmpty(e.detail['menu_type']) && !Util.isEmpty(filter['menu_type'])) {
        delete filter['menu_type'];
      }
      for (const i in e.detail) {
        filter[i] = e.detail[i]
      }
    }

    if (!Util.isEmpty(filter['ids'])) {
      delete filter['ids'];
    }

    for (const k in filter) {
      if (filter[k] && filter[k] != -1) continue
      delete filter[k]
    }

    if (!Util.isEmpty(filter['status'])) {
      this.setData({
        tabIndex: 0,
        statCheckAll: false,
      })
    }

    this.setData({filter: filter})
    if (this.data.tabIndex == 1) {
      this.getStat();
      return
    }

    that.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: []
    });

    that.getLists()
  },

  shopStatDialog(e) {
    const that = this;
    wx.showLoading({
      title: "统计中..."
    })
    that.setData({
      statDialog: true,
      shopStat: {}
    })
    getShopConsoleStat().then(res => {
      that.setData({
        shopStat: res.data || null
      })
    }).catch(errmsg => {
    }).finally(() => {
      wx.hideLoading();
    })
  },

  closeStatLayer(e) {
    this.setData({
      statDialog: false
    })
  },

  closeLayer(e) {
    this.setData({
      printerTypeDialog: false,
      selectIds: null,
      isCheckAll: false
    })
    let lists = this.data.lists || [];
    lists.map(e1 => {
      e1.active = false;
    })
    this.setData({lists: lists})
  },

  shopPrinterDialog(e) {
    const that = this,
      type = e.currentTarget.dataset.type || 0;

    let selectIds = this.data.selectIds || [];
    if (type == 1) {
      selectIds = [];
      selectIds.push(e.currentTarget.dataset.v);
      this.setData({
        selectIds: selectIds,
        isCheckAll: false
      })
    }

    if (Util.isEmpty(selectIds) && !this.data.isCheckAll) {
      return Util.Tips({title: "至少选择一项", hideMask: true});
    }

    this.onLoadTabbar();
    this.setData({
      printerTypeDialog: true,
    })
  },

  goPrinter(e) { //去打印
    const that = this,
      filter = this.data.filter || {},
      selectIds = this.data.selectIds || [];

    let params = [];
    if (Util.isEmpty(selectIds) && !this.data.isCheckAll) {
      return Util.Tips({title: "至少选择一项", hideMask: true});
    }
    params.push("printer_type=" + e.currentTarget.dataset.key);
    for (const k in filter) {
      params.push(k + "=" + filter[k])
    }

    if (selectIds.length) {
      params.push("id=" + selectIds.join("-"));
    }

    wx.navigateTo({
      url: '../console/confirm_printer?' + params.join('&')
    })
  },

  /**
   * 接单
   * @param e
   */
  bindAcceptOrder(e) {
    const that = this,
      type = e.currentTarget.dataset.type || 0;

    let filter = this.data.filter || {},
      selectIds = this.data.selectIds || [];

    if (type == 1) {
      selectIds = [];
      selectIds.push(e.currentTarget.dataset.v);
    }
    if (selectIds.length == 0 && !this.data.isCheckAll) {
      return Util.Tips({title: "请至少选择一个", hideMask: true});
    }
    filter['ids'] = selectIds || [];

    Util.showModelTip("已选中" + (this.data.isCheckAll ? this.data.total : selectIds.length) + "个订单，接单后不允许修改。", "接单确认", "立即接单", "",).then(result => {
      if (result.confirm) {
        wx.showLoading({
          title: "正在接单"
        })
        acceptOrder(filter).then(res => {
          Util.Tips({title: "接单成功", hideMask: true});

          if (!Util.isEmpty(filter['ids'])) {
            delete filter['ids'];

            that.setData({
              filter: filter
            })
          }
          that.setData({
            selectIds: [],
            isCheckAll: false,
            loadend: false,
            loading: false,
            page: 1,
            lists: []
          });
          that.getLists();
        }).finally(() => {
          wx.hideLoading()
        })
      }
    })

  },

  /**
   * 确认出餐
   * @param e
   */
  bindConfirmDeliver(e) {
    const that = this,
      type = e.currentTarget.dataset.type || 0;

    let filter = this.data.filter || {},
      selectIds = this.data.selectIds || [];

    if (type == 1) {
      selectIds = [];
      selectIds.push(e.currentTarget.dataset.v);
    }
    if (selectIds.length == 0 && !this.data.isCheckAll) {
      return Util.Tips({title: "请至少选择一个", hideMask: true});
    }

    filter['ids'] = selectIds;

    Util.showModelTip("已选中" + (this.data.isCheckAll ? this.data.total : selectIds.length) + "个订单，确认出餐后不可修改。", "确认出餐吗", "立即出餐", "",).then(result => {
      if (result.confirm) {
        confirmDeliverOrder(filter).then(res => {
          Util.Tips({title: res.msg || "出餐成功", hideMask: true});
          if (!Util.isEmpty(filter['ids'])) {
            delete filter['ids'];
            that.setData({
              filter: filter
            })
          }

          // console.log("confirm ", filter)
          that.setData({
            selectIds: [],
            isCheckAll: false,
            loadend: false,
            loading: false,
            page: 1,
            lists: []
          });
          that.getLists();
        })
      }
    })
  },

  makePhoneCall(e) {
    const mobile = e.currentTarget.dataset.mobile || ''
    if (!mobile)
      return Util.Tips({title: '手机号码错误', hideMask: true});

    wx.makePhoneCall({
      phoneNumber: mobile
    });

  },

  /**
   * 初始化高度
   * @Author   thomashtao               bosslen
   */
  initTop() {
    const that = this,
      follow_doing = this.data.follow_doing;

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
      that.onLoadTabbar();
    }).then(() => {
      wx.createSelectorQuery().select('.navbar')
        .boundingClientRect((rect) => {
          if (!rect) {
            return;
          }
          let marginTop = rect.height
          if (follow_doing) {
            marginTop += 3
          }

          that.setData({
            marginTop: marginTop,
            top: marginTop + 10
          })
        })
        .exec();

    })
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this;
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;

          let bottom = parseInt(rect.height);
          if (that.data.isIphoneX) {
            bottom += 24;
          } else {
            bottom += 15;
          }
          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      current_date: Util.formatTime(6),
      lists: []
    })

    this.getLists();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getLists();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})